package dispost

import (
	"github.com/astaxie/beego/logs"
	"github.com/hpcloud/tail"
	"io"
	"nodemessage.com/logbase/src/utils"
	"time"
)

var TailConfig = tail.Config{
	ReOpen:    true,
	Follow:    true,
	Location:  &tail.SeekInfo{Offset: 0, Whence: io.SeekEnd},
	MustExist: false,
	Poll:      true,
}

func WatchFileContent(filName string) {
	tails, err := tail.TailFile(filName, TailConfig)
	if err != nil {
		logs.Error(err.Error())
		return
	}
	WatchArray[filName] = tails
	var line *tail.Line
	var ok bool
	go func() {
		for {
			if _, ok := WatchArray[filName]; !ok {
				logs.Info("watch remove :" + filName)
				return
			}
			line, ok = <-tails.Lines
			if !ok {
				logs.Info("tail file close reopen, filename:%s\n", tails.Filename)
				time.Sleep(time.Second)
				continue
			}
			utils.InsertDoc(utils.GetMd5(filName), utils.NewZincDataData(line.Text),
				initConf.ZincUrl, initConf.ZincUserName, initConf.ZincUserPwd)
		}
	}()
}
